import { ref, reactive, onMounted, watch, defineEmits } from 'vue'
import { useUserStore } from '@/store/user'
import { login } from '@/apis/user'

export default function useLoginForm() {
  const LabelMapping: LooseObject = {
    account: '账号',
    password: '密码',
  }

  const showErr = ref(false)
  const loading = ref(false)
  const errMsg = ref('')
  const form = reactive({
    account: '',
    password: '',
  } as LooseObject)

  watch(form, () => {
    errMsg.value = ''
  })

  onMounted(() => {
    loading.value = false
    const loginForm = localStorage.getItem('login_form')

    if (loginForm) {
      const data = JSON.parse(loginForm)
      Object.keys(form).forEach((key: string) => {
        form[key] = data[key]
      })
    }
  })

  const formInvalid = () => {
    showErr.value = false
    return Object.keys(form).some((key: string) => {
      const formValue = form[key]
      if (!formValue) {
        showErr.value = true
        errMsg.value = `请输入${LabelMapping[key]}`
      }
      return !formValue
    })
  }

  const initUserInfo = (data, callback?) => {
    const userStore = useUserStore()
    userStore.$patch(data)
    callback && callback()
    localStorage.setItem('user_info', JSON.stringify(data))
    localStorage.setItem('login_form', JSON.stringify(form))
  }

  const submit = async (callback?) => {
    if (formInvalid()) {
      return
    }
    if (loading.value) {
      return
    }
    loading.value = true

    login(form).then(async (res: any) => {
      const { app_list = [{}] } = res
      // 用户信息传入
      initUserInfo({ ...res, smartToken: res.token, appId: '57accc0caa7e422f9b32c3584eb2ac6c' || app_list[0].id }, callback)
    })
      .catch((err: any) => {
        showErr.value = true
        errMsg.value = err?.data?.error_reason ? err.data.error_reason : err
        loading.value = false
      })
  }

  return {
    showErr,
    loading,
    errMsg,
    form,
    submit,
  }
}